package com.hua.api.modules.express.service.impl;


import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.hua.api.core.constants.Status;
import com.hua.api.core.framework.http.response.OpenApiResponse;
import com.hua.api.core.framework.util.exception.ApiError;
import com.hua.api.core.out.express.imdada.domain.*;
import com.hua.api.core.out.express.imdada.request.*;

import com.hua.api.core.out.express.ishansong.domain.IssStatus;
import com.hua.api.core.properties.SysProperties;
import com.hua.api.core.util.NumberUtil;
import com.hua.api.core.util.StringUtil;
import com.hua.api.core.util.ValidationUtil;
import com.hua.api.modules.express.dao.ExpressOrderDao;
import com.hua.api.modules.express.domain.ExpressOrder;
import com.hua.api.modules.express.domain.ShopInfoExpress;
import com.hua.api.modules.express.repository.ShopInfoExpressRepository;
import com.hua.api.modules.express.service.ExpressInfoService;
import com.hua.api.modules.express.service.dto.ExpressInfoCriteria;
import com.hua.api.modules.express.util.ExpressOrderUtil;
import com.hua.api.modules.finance.domain.UserAccount;
import com.hua.api.modules.finance.service.UserAccountService;
import com.hua.api.modules.order.dao.ShopInfoDao;
import com.hua.api.modules.order.domain.OrderInfo;
import com.hua.api.modules.order.domain.ShopInfo;
import com.hua.api.modules.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 闪送物流对接接口
 * */
@SuppressWarnings("all")
@Slf4j
@Component("imdada")
public class ImDadaExpressInfoServiceImpl implements ExpressInfoService {

    @Autowired
    public ShopInfoDao shopInfoDao;

    @Autowired
    public ExpressOrderDao expressOrderDao;

    @Autowired
    public ShopInfoExpressRepository shopInfoExpressRepository;

    @Autowired
    public OrderInfoService orderInfoService;

    @Autowired
    public UserAccountService userAccountService;

    @Autowired
    public SysProperties sysProperties;

    @Override
    public JSONObject openCitiesLists() {
        return null;
    }

    @Override
    public JSONObject queryAllStores(ExpressInfoCriteria criteria) {
        ShopDetailRequest request = new ShopDetailRequest();
        CommonParam param = new CommonParam();
        param.setOrigin_shop_id(criteria.getStoreId());
        request.setParam(param);
        OpenApiResponse response = request.doRequest();
        return response.toJSONObject();
    }

    /**
     * {"status":"success","result":
     * {"station_name":"花千束合木山庄店",
     * "area_name":"昌平区",
     * "settlementType":0,
     * "approveStatus":-1,
     * "station_address":"北京市昌平区九台路8号附近合木山庄E18-B座E08B座",
     * "contact_name":"赵",
     * "origin_shop_id":"1358361337-11675614102",
     * "business":3,"lng":116.393486,"id_card":"",
     * "bd_phone":"15021612720",
     * "merchant_id":1358361337,
     * "city_name":"北京",
     * "phone":"13611216920",
     * "bd_name":"余檬","lat":40.084601,"status":1},"code":0,"msg":"成功","fail":false,"success":true}
     * */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject storeOpertionSync(String storeId, String expressCode, Integer shopId) {

        ShopDetailRequest request = new ShopDetailRequest();
        CommonParam param = new CommonParam();
        param.setOrigin_shop_id(storeId);
        request.setParam(param);
        OpenApiResponse response = request.doRequest();
        if(!response.isError){
            JSONObject result = response.toJSONObject().getJSONObject("result");
            String station_name = result.getString("station_name");
            String area_name = result.getString("area_name");
            String city_name = result.getString("city_name");
            String station_address = result.getString("station_address");
            Double lng = result.getDouble("lng");
            Double lat = result.getDouble("lat");
            String contact_name = result.getString("contact_name");
            String phone = result.getString("phone");

            ShopInfoExpress shopInfoExpress = shopInfoExpressRepository.findByStoreId(storeId);
            if(null!=shopInfoExpress){
                throw ApiError.Type.LOGIC_ERROR.toException("storeId店铺信息已经存在！ storeId="+storeId);
            }
            ShopInfo shopInfo = shopInfoDao.getObject(ShopInfo.class, shopId);
            ValidationUtil.requireNotNull(shopInfo,"店铺信息不存在！");

            ShopInfoExpress sie = new ShopInfoExpress();
            sie.setShopId(shopId);
            sie.setExpressCode(expressCode);
            sie.setStoreId(storeId);
            sie.setStoreName(station_name);
            sie.setCityName(city_name);
            sie.setAddress(station_address);
            sie.setAddressDetail(station_address);
            sie.setContactsMobile(phone);
            sie.setGeoType("gaode");
            sie.setLatitude(lat);
            sie.setLongitude(lng);
            sie.setStatus(Status.LOGIC_Y);
            shopInfoExpressRepository.save(sie);

            return response.toJSONObject();
        }else {
            throw ApiError.Type.LOGIC_ERROR.toException(response.errMsg);
        }
    }

    @Override
    public JSONObject getUserAccount() {
        BalanceQueryRequest request = new BalanceQueryRequest();
        CommonParam param = new CommonParam();
        param.setCategory(3);
        request.setParam(param);
        OpenApiResponse response = request.doRequest();
        if(!response.isError){
            return response.toJSONObject();
        }else{
            throw ApiError.Type.LOGIC_ERROR.toException(response.errMsg);
        }
    }

    @Override
    public ExpressOrder orderCalculate(ShopInfoExpress express, OrderInfo order, UserAccount account,Integer isSaleAfter) {
        ExpressOrder eorder = ExpressOrderUtil.getExpressOrder(express,order);
        eorder.setIsSaleAfter(0);
        QueryDeliverFeeRequest request = new QueryDeliverFeeRequest();
        OrderInfoParam param = new OrderInfoParam();
        param.setShop_no(eorder.getStoreId());
        param.setOrigin_id(eorder.getExpressOrderNo());
        param.setCargo_price(100d); // 订单金额(是商品订单的金额，不是物流订单的金额)
        param.setIs_prepay(0);
        param.setReceiver_name(eorder.getToReceiveName());
        param.setReceiver_phone(eorder.getToMobile());
        param.setReceiver_address(eorder.getToAddress());
        param.setCargo_weight(1d);
        param.setReceiver_lat(eorder.getToLatitude());
        param.setReceiver_lng(eorder.getToLongitude());
        param.setCallback(sysProperties.imDadaCallback);
        request.setParam(param);
        OpenApiResponse response = request.doRequest();
        if(!response.isError){
            JSONObject res = response.toJSONObject();
            JSONObject result = res.getJSONObject("result");
            Double distance = result.getDouble("distance");
            Double fee = result.getDouble("fee"); // 实际运费(单位：元)，运费减去优惠券费用
            Double deliverFee = result.getDouble("deliverFee"); // 	运费(单位：元)
            String deliveryNo = result.getString("deliveryNo"); // 单号
            Double insuranceFee = result.getDouble("insuranceFee"); // 保价费(单位：元)
            Double couponFee = result.getDouble("couponFee");
            Double tips = result.getDouble("tips"); // 小费
            eorder.setDistance(distance.intValue());
            eorder.setRealFee(NumberUtil.yuanToFen(fee)); // 实际运费
            eorder.setAddFee(NumberUtil.yuanToFen(tips)); // 小费
            eorder.setTotalAmount(NumberUtil.yuanToFen(deliverFee)); // 总运费
            eorder.setCouponFee(NumberUtil.yuanToFen(couponFee));
            eorder.setThirdOrderNo(deliveryNo);
            eorder.setChargeSource(Status.CHARGE_HUAYT);

            // 账户余额判断
            if(account.getAmountMoney()<eorder.getRealFee()/100d){
                throw ApiError.Type.EXPRESS_API_ERROR.toException("您的账户余额不足 userId:"+account.getUserId());
            }

            return eorder;
        }else {
            throw ApiError.Type.LOGIC_ERROR.toException(response.errMsg);
        }
    }


    @Override
    public ExpressOrder orderPlace(ExpressOrder eorder) {
        AddAfterQueryRequest request = new AddAfterQueryRequest();
        CommonParam param = new CommonParam();
        param.setDeliveryNo(eorder.getThirdOrderNo());
        request.setParam(param);
        OpenApiResponse response = request.doRequest();
        if(!response.isError){
            eorder.setOrderTime(new Date());
            eorder.setChargeSource(Status.CHARGE_HUAYT);
            return eorder;
        }else {
            throw ApiError.Type.LOGIC_ERROR.toException(response.errMsg);
        }

    }

    @Override
    public JSONObject courierInfo(ExpressInfoCriteria criteria) {
        return null;
    }

    @Override
    public JSONObject abortOrder(ExpressInfoCriteria criteria) {

        ExpressOrder eorder = expressOrderDao.findByExpressOrderNo(criteria.getExpressOrderNo());
        ValidationUtil.requireNotNull(eorder,"物流单信息不存在！");

        FormalCancelRequest request = new FormalCancelRequest();
        CommonParam param = new CommonParam();
        param.setOrder_id(eorder.getExpressOrderNo());
        param.setCancel_reason_id(10000);
        param.setCancel_reason("重新安排，取消配送！");
        request.setParam(param);
        OpenApiResponse response = request.doRequest();

        if(!response.isError){
            JSONObject result = response.toJSONObject().getJSONObject("result");
            Integer deduct = 0; // 扣除的违约金(单位：分)

            Integer sendBackFee =  0; // 返回金额
            JSONObject data = new JSONObject();
            if(result.containsKey("deduct_fee")){
                Double deductFee = result.getDouble("deduct_fee"); // 扣除的违约金(单位：元)
                deduct = NumberUtil.yuanToFen(deductFee); //分
                sendBackFee =  eorder.getRealFee()-deduct;
            }
            data.put("sendBackFee",sendBackFee); //返回金额（分）
            data.put("deductAmount",deduct); //取消扣除金额 (分)

            return data;
        }else {
            throw ApiError.Type.LOGIC_ERROR.toException(response.errMsg);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject addition(ExpressOrder eorder, Integer fenMoney) {

        AddTipsRequest request = new AddTipsRequest();
        CommonParam param = new CommonParam();
        param.setOrder_id(eorder.getExpressOrderNo());
        param.setTips(fenMoney/100d);
        request.setParam(param);
        OpenApiResponse response = request.doRequest();
        if(!response.isError){
            return response.toJSONObject();
        }else {
            throw ApiError.Type.LOGIC_ERROR.toException(response.errMsg);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject storeOperationAdd(Integer shopId,String expressCode) {
        log.info("IssExpressInfoServiceImpl.storeOperationAdd(shopId={},expressCode={})",shopId,expressCode);
        ShopInfo shopInfo = shopInfoDao.getObject(ShopInfo.class, shopId);
        ValidationUtil.requireNotNull(shopInfo,"店铺数据不存在！ shopId="+shopId);
        ShopAddRequest request = new ShopAddRequest();
        ShopInfoParam param = new ShopInfoParam();
        param.setBusiness(3);
        param.setStation_name(shopInfo.getShopName());
        param.setStation_address(shopInfo.getTown()+shopInfo.getShopAddress());
        param.setPhone(shopInfo.getPhoneNumber());
        param.setContact_name(shopInfo.getContactUser());
        param.setLat(shopInfo.getLatitude());
        param.setLng(shopInfo.getLongitude());
        request.setParam(param);
        OpenApiResponse response = request.doRequest();
        /**
         * {"result":
         * {"successList":
         *  [{"business":3,"lng":116.29068172261903,"phone":"13260492696","contactName":"马先生","originShopId":"1358361337-11675614085","stationName":"兆丰家园鲜花店","stationAddress":"北京市昌平区沙河镇丰善家园东区底商1088兆丰鲜花店","lat":40.15804325191729}],
         *
         *  "success":1,"failedList":[]},"msg":"成功","fail":false,"code":0,"success":true,"status":"success"}
         * */
        if(!response.isError){
            log.info(response.toJSONObject().toString());
            JSONObject result = response.toJSONObject().getJSONObject("result");
            JSONArray array = result.getJSONArray("successList");
            if(array.size()>0){
                JSONObject data = array.getJSONObject(0);

                String phone = data.getString("phone");
                String contactName = data.getString("contactName");
                String originShopId = data.getString("originShopId");
                String shopName = data.getString("stationName");
                String address = data.getString("stationAddress");
                Double lat = data.getDouble("lat");
                Double lng = data.getDouble("lng");

                ShopInfoExpress shopInfoExpress = new ShopInfoExpress();
                shopInfoExpress.setShopId(shopId);
                shopInfoExpress.setStoreId(originShopId);
                shopInfoExpress.setExpressCode(expressCode);
                shopInfoExpress.setStoreName(shopInfo.getShopName());
                shopInfoExpress.setAddress(shopInfo.getTown());
                shopInfoExpress.setCityName(shopInfo.getCity());
                shopInfoExpress.setAddressDetail(shopInfo.getShopAddress());
                shopInfoExpress.setLatitude(shopInfo.getLatitude());
                shopInfoExpress.setLongitude(shopInfo.getLongitude());
                shopInfoExpress.setGeoType("gaode");
                shopInfoExpress.setStatus(1);
                shopInfoExpress.setContactsMobile(shopInfo.getPhoneNumber());
                shopInfoDao.saveObject(shopInfoExpress);
            }
            return new JSONObject();
        }else {
            throw ApiError.Type.LOGIC_ERROR.toException(response.errMsg);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject storeOperationModify(Integer shopId, String expressCode, String storeId) {
        log.info("ImDadaExpressInfoServiceImpl.storeOperationModify(shopId={},expressCode={})",shopId,expressCode);
        ShopInfoExpress exp = shopInfoExpressRepository.findByStoreId(storeId);
        ValidationUtil.requireNotNull(exp,"店铺数据不存在！ shopId="+shopId);
        ShopInfo shopInfo = shopInfoDao.getObject(ShopInfo.class, shopId);
        ValidationUtil.requireNotNull(shopInfo,"店铺数据不存在！ shopId="+shopId);
        ShopUpdateRequest request = new ShopUpdateRequest();
        ShopInfoParam param = new ShopInfoParam();
        param.setBusiness(3);
        param.setStation_name(shopInfo.getShopName());
        param.setStation_address(shopInfo.getTown()+shopInfo.getShopAddress());
        param.setPhone(shopInfo.getPhoneNumber());
        param.setContact_name(shopInfo.getContactUser());
        param.setLat(shopInfo.getLatitude());
        param.setLng(shopInfo.getLongitude());
        param.setOrigin_shop_id(exp.getStoreId());
        request.setParam(param);
        OpenApiResponse response = request.doRequest();
        if(!response.isError){
            log.info(response.toJSONObject().toString());

            exp.setStoreName(shopInfo.getShopName());
            exp.setAddress(shopInfo.getTown());
            exp.setAddressDetail(shopInfo.getShopAddress());
            exp.setContactsMobile(shopInfo.getPhoneNumber());
            exp.setLatitude(shopInfo.getLatitude());
            exp.setLongitude(shopInfo.getLongitude());
            exp.setCityName(shopInfo.getCity());
            shopInfoExpressRepository.save(exp);

            return new JSONObject();
        }else {
            throw ApiError.Type.LOGIC_ERROR.toException(response.errMsg);
        }
    }


    /**
     *
     * 订单状态(待接单＝1,待取货＝2,骑士到店=100,配送中＝3,已完成＝4,已取消＝5, 已追加待接单=8,
     * 妥投异常之物品返回中=9, 妥投异常之物品返回完成=10, 售后取件单送达门店=6, 创建达达运单失败=1000）
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void onOrderStatusChange(JSONObject data) {
        log.info("ImDadaExpressInfoServiceImpl.onOrderStatusChange() body={}",data.toString());
        String sign = getSign(data.getString("client_id"),data.getString("order_id"),data.getString("update_time"));
        String  signature = StringUtil.dealNull(data.getString("signature"));
        log.info("sign={},signature={}",sign,signature);
        if(!StringUtil.equals(sign,signature)){
            log.warn("签名判断错误！");
            return;
        }
        String expressOrderNo = data.getString("order_id");
        ExpressOrder expressOrder = expressOrderDao.findByExpressOrderNo(expressOrderNo);
        ValidationUtil.requireNotNull(expressOrder,"物流单号不存在！ issOrderNo="+expressOrderNo);
        Integer orderStatus = data.getInteger("order_status");
        ImDadaStatus imDadaStatus = ImDadaStatus.fromValue(orderStatus);
        log.info("onOrderStatusChange issOrderNo={} statusName={}",expressOrderNo,imDadaStatus.name());
        if(imDadaStatus==ImDadaStatus.daijiedan){
            // 待接单
            onExpressOrderPaidan(expressOrder,data);
        }else if(imDadaStatus == ImDadaStatus.daiquhuo){
            // 已接单 待取货
            onExpressOrderJiedan(expressOrder,data);
        }else if(imDadaStatus == ImDadaStatus.peisongzhong){
            // 已取货，配送中
            onExpressOrderPeisong(expressOrder,data);
        }else if(imDadaStatus == ImDadaStatus.yisongda){
            // 已送达
            onExpressOrderSongda(expressOrder,data);
        }else if(imDadaStatus == ImDadaStatus.quxiao){
            // 已取消
            onExpressOrderQuxiao(expressOrder,data);
        }else if(imDadaStatus == ImDadaStatus.chongpeishong){
            // 已追加待接单
            log.warn("onOrderStatusChange  已追加待接单 expressOrderNo={} statusName={}",expressOrderNo,imDadaStatus.name());
        }else if(imDadaStatus == ImDadaStatus.fanhuizhong){
            // 妥投异常之物品返回中
            log.warn("onOrderStatusChange  妥投异常之物品返回中 expressOrderNo={} statusName={}",expressOrderNo,imDadaStatus.name());

        }else if(imDadaStatus == ImDadaStatus.fanhuiwancheng){
            // 妥投异常之物品返回完成
            log.warn("onOrderStatusChange  妥投异常之物品返回完成 expressOrderNo={} statusName={}",expressOrderNo,imDadaStatus.name());

        }else if(imDadaStatus == ImDadaStatus.shouhoufanhui){
            // 妥投异常之物品返回完成
            log.warn("onOrderStatusChange  售后取件单送达门店 expressOrderNo={} statusName={}",expressOrderNo,imDadaStatus.name());

        }else if(imDadaStatus == ImDadaStatus.fail){
            // 创建达达运单失败
            log.warn("onOrderStatusChange  创建达达运单失败 expressOrderNo={} statusName={}",expressOrderNo,imDadaStatus.name());
        }
    }


    // https://newopen.imdada.cn/#/development/file/order 签名规则
    private String getSign(String clientId,String orderId,String updateTime) {
        //  对client_id, order_id, update_time的值进行字符串升序排列，再连接字符串，取md5值
        StringBuffer sbf = new StringBuffer();
        List<String> list = new ArrayList<>();
        list.add(clientId);
        list.add(orderId);
        list.add(updateTime);
        Object[] arrays = list.toArray();
        Arrays.sort(arrays);
        for(Object object:arrays){
            sbf.append(StringUtil.dealNull(object));
        }
        String src = sbf.toString();
        return  SecureUtil.md5(src);
    }

    // 派单中
    private void onExpressOrderPaidan(ExpressOrder expressOrder,JSONObject data){

        Status.LogisticsStatus logisticsStatus = Status.LogisticsStatus.fromValue(expressOrder.getOrderStatus());
        log.info("ImDadaExpressInfoServiceImpl.onExpressOrderPaidan ThirdOrderN = {}, logisticsStatus = {}",expressOrder.getThirdOrderNo(),logisticsStatus.name());
        if(logisticsStatus == Status.LogisticsStatus.daipeisong || logisticsStatus == Status.LogisticsStatus.yiquxiao){
            log.info("ImDadaExpressInfoServiceImpl，派单中 thirdOrderNo={}",expressOrder.getThirdOrderNo());
            expressOrder.setOrderStatus( Status.LogisticsStatus.daijiedan.getValue());
            expressOrderDao.updateObject(expressOrder);
            OrderInfo orderInfo = expressOrderDao.getObject(OrderInfo.class,expressOrder.getOrderId());
            if(null!=orderInfo && !StringUtil.equals(expressOrder.getIsSaleAfter(),Status.LOGIC_Y)){
                orderInfoService.onOrderInfoSendPaidan(orderInfo.getOrderNo(),expressOrder.getId().intValue());
            }
        }
    }

    // 接单
    private void onExpressOrderJiedan(ExpressOrder expressOrder,JSONObject data){
        log.info("ImDadaExpressInfoServiceImpl.onExpressOrderJiedan={}",expressOrder.getExpressOrderNo());
        Status.LogisticsStatus logisticsStatus = Status.LogisticsStatus.fromValue(expressOrder.getOrderStatus());
        if(logisticsStatus == Status.LogisticsStatus.daijiedan || logisticsStatus == Status.LogisticsStatus.daipeisong){
            log.info("ImDadaExpressInfoServiceImpl，待取货 thirdOrderNo={}",expressOrder.getThirdOrderNo());
            expressOrder.setOrderStatus( Status.LogisticsStatus.yijiedan.getValue());
            String dm_name = data.getString("dm_name");
            String dm_mobile = data.getString("dm_mobile");
            // 配送员信息
            expressOrder.setCourierName(dm_name);
            expressOrder.setCourierMobile(dm_mobile);
            expressOrderDao.updateObject(expressOrder);
            OrderInfo orderInfo = expressOrderDao.getObject(OrderInfo.class,expressOrder.getOrderId());
            if(null!=orderInfo && !StringUtil.equals(expressOrder.getIsSaleAfter(),Status.LOGIC_Y)){
                orderInfoService.onOrderInfoSendJiedan(orderInfo.getOrderNo(),dm_name,dm_mobile);
            }
        }

    }

    // 配送中
    private void onExpressOrderPeisong(ExpressOrder expressOrder,JSONObject data){
        log.info("ImDadaExpressInfoServiceImpl.onExpressOrderPeisong={}",expressOrder.getThirdOrderNo());
        Status.LogisticsStatus logisticsStatus = Status.LogisticsStatus.fromValue(expressOrder.getOrderStatus());
        if(logisticsStatus == Status.LogisticsStatus.yijiedan ||
                logisticsStatus == Status.LogisticsStatus.daijiedan ||
                logisticsStatus == Status.LogisticsStatus.daipeisong){
            log.info("ImDadaExpressInfoServiceImpl，配送中 thirdOrderNo={}",expressOrder.getThirdOrderNo());
            expressOrder.setOrderStatus( Status.LogisticsStatus.peisongzhong.getValue());
            expressOrderDao.updateObject(expressOrder);

            OrderInfo orderInfo = expressOrderDao.getObject(OrderInfo.class,expressOrder.getOrderId());
            if(null!=orderInfo && !StringUtil.equals(expressOrder.getIsSaleAfter(),Status.LOGIC_Y)){
                orderInfoService.onOrderInfoSendPeisong(orderInfo.getOrderNo());
            }

        }
    }
    // 送达
    private void onExpressOrderSongda(ExpressOrder expressOrder,JSONObject data){
        log.info("ImDadaExpressInfoServiceImpl.onExpressOrderSongda（）={}",expressOrder.getThirdOrderNo());
        Status.LogisticsStatus logisticsStatus = Status.LogisticsStatus.fromValue(expressOrder.getOrderStatus());
        if(logisticsStatus == Status.LogisticsStatus.yijiedan ||
                logisticsStatus == Status.LogisticsStatus.daijiedan ||
                logisticsStatus == Status.LogisticsStatus.daipeisong ||
                logisticsStatus==Status.LogisticsStatus.peisongzhong){
            log.info("物流单已接单，待取货 thirdOrderNo={}",expressOrder.getThirdOrderNo());
            expressOrder.setOrderStatus( Status.LogisticsStatus.yisongda.getValue());
            expressOrderDao.updateObject(expressOrder);
            OrderInfo orderInfo = expressOrderDao.getObject(OrderInfo.class,expressOrder.getOrderId());
            if(null!=orderInfo && !StringUtil.equals(expressOrder.getIsSaleAfter(),Status.LOGIC_Y)){
                orderInfoService.onOrderInfoSendSongda(orderInfo.getOrderNo());
            }
        }
    }

    // 取消
    private void onExpressOrderQuxiao(ExpressOrder expressOrder,JSONObject data){
        log.info("ImDadaExpressInfoServiceImpl.onExpressOrderQuxiao={}",expressOrder.getThirdOrderNo());
        Status.LogisticsStatus logisticsStatus = Status.LogisticsStatus.fromValue(expressOrder.getOrderStatus());
        if(logisticsStatus == Status.LogisticsStatus.daijiedan ||
                logisticsStatus == Status.LogisticsStatus.yijiedan ||
                logisticsStatus == Status.LogisticsStatus.peisongzhong){
            log.info("物流单已取消 thirdOrderNo={}",expressOrder.getThirdOrderNo());
            OrderInfo orderInfo = expressOrderDao.getObject(OrderInfo.class,expressOrder.getOrderId());
            expressOrder.setOrderStatus( Status.LogisticsStatus.yiquxiao.getValue());
            Integer backFee = expressOrder.getRealFee()-expressOrder.getPunishAmount(); // 支付金额-取消罚金
            Double backYuan = backFee/100d; // (元)
            log.info(" onExpressOrderQuxiao 取消配送，返回费用 backYuan={}元",backYuan);
            // 退款操作
            if(null!=orderInfo && expressOrder.getBackFee()==0){
                if(backYuan>0){
                    userAccountService.onUserAccountAddUseShopId(orderInfo.getShopId(),backYuan,"express_order","取消物流返回费用，单号:"+expressOrder.getExpressOrderNo());
                    expressOrder.setBackFee(backFee);
                }
            }
            expressOrderDao.updateObject(expressOrder);

            if(null!=orderInfo && !StringUtil.equals(expressOrder.getIsSaleAfter(),Status.LOGIC_Y)){
                orderInfoService.onOrderInfoSendQuxiao(orderInfo.getOrderNo());
            }
        }else{


            OrderInfo orderInfo = expressOrderDao.getObject(OrderInfo.class,expressOrder.getOrderId());
            if(null!=orderInfo && expressOrder.getBackFee()==0 ){
                Integer backFee = expressOrder.getRealFee()-expressOrder.getPunishAmount(); // 支付金额-取消罚金
                Double backYuan = backFee/100d; // (元)
                log.info(" onExpressOrderQuxiao 取消配送，返回费用 backYuan={}元",backYuan);
                if(backYuan>0){
                    userAccountService.onUserAccountAddUseShopId(orderInfo.getShopId(),backYuan,"express_order","取消物流返回费用，单号:"+expressOrder.getExpressOrderNo());
                    expressOrder.setBackFee(backFee);
                    expressOrderDao.updateObject(expressOrder);

                }
            }



        }

    }




}
